package com.limh.readers.utils

import com.google.gson.Gson
import com.google.gson.JsonArray
import com.google.gson.JsonParser
import org.json.JSONException


/**
 * Function:
 * author: limh
 * time:2017/7/11
 */
object GsonUtils {
    var gson: Gson = Gson()

    /**
     * Bean转String
     */
    fun <T> Gson2Str(gs: T): String {
        return gson.toJson(gs)
    }

    /**
     * string转Bean
     */
    fun <T> str2Bean(gsonString: String, cls: Class<T>): T {
        return gson.fromJson(gsonString, cls)
    }

    /**
     * list<T>转String
     */
    fun <T> list2Str(list: List<T>): String {
        val arry = JsonArray()
        for (item in list)
            arry.add(Gson2Str(item))
        return arry.toString()
    }

    /**
     * str转List<T>
     */
    fun <T> str2List(str: String, cls: Class<T>): MutableList<T> {
        val datas = ArrayList<T>()
        try {
            val array = JsonParser().parse(str).asJsonArray
            for (i in 0..array.size() - 1) {
                datas.add(str2Bean(array[i].toString(), cls))
            }
        } catch (e: JSONException) {
            System.out.println("异常=" + e.message)
            e.printStackTrace()
        }
        return datas
    }

    /**
     * str转List<T>
     */
    fun <T> str2List(str: List<String>, cls: Class<T>): ArrayList<T> {
        val datas = ArrayList<T>()
        try {
            for (item in str) {
                datas.add(str2Bean(item, cls))
            }
        } catch (e: JSONException) {
            System.out.println("异常=" + e.message)
            e.printStackTrace()
        }
        return datas
    }
}